import { ERROR_STATUS } from '@/config'
import { getToken } from '@/store'
import { createError } from '@/utils'

/**
 * 添加基础请求头
 */
export const baseRequestInterceptor: requestInterceptor = (requestConfig: RequestConfig) => {
  requestConfig.header = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    ...requestConfig.header,
  }

  return requestConfig
}

/**
 * 添加token，请求拦截器
 */
export const tokenRequestInterceptor: requestInterceptor = (requestConfig: RequestConfig) => {
  const token = getToken()
  requestConfig.header = {
    'jsessionid': token,
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    ...requestConfig.header,
  }

  return requestConfig
}

/**
 * 状态码响应拦截器
 */
export const statusResponseInterceptor: responseInterceptor = (result) => {
  const { statusCode } = result

  if (statusCode !== 200)
    throw createError(ERROR_STATUS[statusCode])

  return result
}

/**
 * 返回值响应拦截器
 */
export const resultResponseInterceptor: responseInterceptor = (res) => {
  const { retcode, retinfo, result, success } = res.data as Result
  if (retcode === 0 || success) {
    // 通用成功
    return result
  }
  /** 处理响应 */
  // else if ([code, code].includes(retcode)) {
  //   // 登录过期
  //   // 将导航栏信息存储 不清空
  //   relaunch(Pages.登录)
  //   throw createError('登录过期，请重新登录！')
  // }
  // else if ([code].includes(retcode)) {
  //   // 未登录
  //   // 将导航栏信息存储 不清空
  //   relaunch(Pages.登录)
  //   throw createError('请登录！')
  // }
  // else if (retcode === code) {
  //   clearUserInfo()
  //   return relaunch(Pages.封禁)
  // }
  else if (retinfo) {
    // 通用失败
    throw createError(retinfo)
  }
  else {
    // 特殊状态码
    throw retcode
  }
}
